package com.example.a13001.shoppingmalltemplate.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.adapters.AddressAdapter;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.modle.Address;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.mvpview.AdressManagerView;
import com.example.a13001.shoppingmalltemplate.presenter.AdressManagerPredenter;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AdressManagerActivity extends BaseActivity implements AddressAdapter.deleteInterface, AddressAdapter.defaultAddressInterface {

    @BindView(R.id.tv_title_center)
    TextView title;
    @BindView(R.id.lv_address)
    ListView lvAddress;
    @BindView(R.id.refresh_addresslist)
    SmartRefreshLayout refreshAddresslist;
    @BindView(R.id.ViewLoading)
    LinearLayout ViewLoading;
//    @BindView(R.id.error)
//    LinearLayout error;
    private List<Address.DeliveryAddressListBean> mList;
    private AddressAdapter mAdapter;
    private static final String TAG = "AdressManagerActivity";
    private AdressManagerPredenter adressManagerPredenter = new AdressManagerPredenter(AdressManagerActivity.this);
    private int pageindex = 1;
    private String safetyCode;
    private String code;
    private String timeStamp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adress_manager);
        ButterKnife.bind(this);
        initData();
//        if (error != null) {
//            error.setVisibility(View.GONE);
//        }
        setRefresh();


    }

    /**
     * 初始化数据源
     */
    private void initData() {
        adressManagerPredenter.onCreate();
        adressManagerPredenter.attachView(adressManagerView);

        title.setText("收货地址管理");

        mList = new ArrayList<>();
        mAdapter = new AddressAdapter(this, mList);
        lvAddress.setAdapter(mAdapter);
        mAdapter.setDeleteInterface(this);
        mAdapter.setDefaultInterface(this);
        lvAddress.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent data=new Intent();
                data.putExtra("address",mList.get(i));
                setResult(44,data);
                finish();
            }
        });
        safetyCode = MyUtils.getMetaValue(AdressManagerActivity.this, "safetyCode");
        code = Utils.md5(safetyCode + Utils.getTimeStamp());
        timeStamp = Utils.getTimeStamp();
        Log.e(TAG, "onCreate: " + code + "-===" + Utils.getTimeStamp());
    }

    private void setRefresh() {
        //刷新
        refreshAddresslist.setRefreshHeader(new ClassicsHeader(AdressManagerActivity.this));
        refreshAddresslist.setRefreshFooter(new ClassicsFooter(AdressManagerActivity.this));
//        mRefresh.setEnablePureScrollMode(true);
        refreshAddresslist.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageindex = 1;
                if (mList != null) {
                    mList.clear();
                }
                adressManagerPredenter.getAdressList(AppConstants.COMPANY_ID, code, timeStamp, AppConstants.PAGE_SIZE, pageindex, 0, "");
                refreshlayout.finishRefresh(2000/*,true*/);//传入false表示刷新失败
            }
        });
        refreshAddresslist.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
//                pageindex++;
//                adressManagerPredenter.getAdressList(AppConstants.COMPANY_ID, code, timeStamp, AppConstants.PAGE_SIZE, pageindex, 0, "");

                refreshlayout.finishLoadMore(2000/*,true*/);//传入false表示加载失败
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mList != null) {
            mList.clear();
        }
        adressManagerPredenter.getAdressList(AppConstants.COMPANY_ID, code, timeStamp, AppConstants.PAGE_SIZE, pageindex, 0, "");
    }

    AdressManagerView adressManagerView = new AdressManagerView() {
        @Override
        public void onSuccess(Address address) {
            Log.e(TAG, "onSuccess: " + address.toString());
            ViewLoading.setVisibility(View.GONE);
//            if (error != null) {
//                error.setVisibility(View.GONE);
//            }
            refreshAddresslist.finishRefresh();
            refreshAddresslist.finishLoadMore();
            int status = address.getStatus();
            if (status > 0) {
                mList.addAll(address.getDelivery_AddressList());
                mAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(AdressManagerActivity.this, "" + address.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        //删除收货地址
        @Override
        public void onSuccessDeleteAddress(CommonResult commonResult) {
            Log.e(TAG, "onSuccessDeleteAddress: " + commonResult.toString());
//            if (error != null) {
//                error.setVisibility(View.GONE);
//            }
            int status = commonResult.getStatus();
            if (status > 0) {
                if (mList != null) {
                    mList.clear();
                }
                adressManagerPredenter.getAdressList(AppConstants.COMPANY_ID, code, timeStamp, AppConstants.PAGE_SIZE, pageindex, 0, "");
            } else {
                Toast.makeText(AdressManagerActivity.this, "" + commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        //设置默认收货地址
        @Override
        public void onSuccessSetDefaultAddress(CommonResult commonResult) {
            Log.e(TAG, "onSuccessSetDefaultAddress: " + commonResult.toString());
//            if (error != null) {
//                error.setVisibility(View.GONE);
//            }
            int status = commonResult.getStatus();
            if (status > 0) {
                if (mList != null) {
                    mList.clear();
                }
                adressManagerPredenter.getAdressList(AppConstants.COMPANY_ID, code, timeStamp, AppConstants.PAGE_SIZE, pageindex, 0, "");
            } else {
                Toast.makeText(AdressManagerActivity.this, "" + commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }


        @Override
        public void onError(String result) {
            if (refreshAddresslist != null) {

                refreshAddresslist.finishRefresh();
                refreshAddresslist.finishLoadMore();
            }
            if (ViewLoading != null) {
                ViewLoading.setVisibility(View.GONE);
            }
//            if (error != null) {
//                error.setVisibility(View.VISIBLE);
//            }

        }
    };


    @OnClick({R.id.iv_title_back, R.id.btn_newaddress})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_back:
                onBackPressed();
                break;
            case R.id.btn_newaddress:
                startActivity(new Intent(this, NewAddressActivity.class));
                break;
        }
    }

    /**
     * 删除地址
     *
     * @param position
     */
    @Override
    public void doDelete(int position) {

        adressManagerPredenter.deleteAddress(AppConstants.COMPANY_ID, code, timeStamp, String.valueOf(mList.get(position).getAddresslId()));
    }

    /**
     * 设置默认地址
     *
     * @param position
     */
    @Override
    public void setDefault(int position) {
        adressManagerPredenter.setDefaultAddress(AppConstants.COMPANY_ID, code, timeStamp, String.valueOf(mList.get(position).getAddresslId()));
    }
}
